﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Skybot.Arcgis.Client.TileLayerExpand;
using ESRI.ArcGIS.Client.Geometry;

namespace ArcgisStudy
{
    using ESRI.ArcGIS.Client.Bing;
    using ESRI.ArcGIS.Client;
    using ESRI.ArcGIS.Client.Symbols;
    using Skybot.Arcgis.Client.TileLayerExpand;
    public partial class About : Page
    {
        public About()
        {
            InitializeComponent();
        }

        // E当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //1321211021122331
            TileLayerBingMapExpand layer = new TileLayerBingMapExpand(new Uri("http://localhost/tiles/r{quadkey}.png?g=49"),
16, 1);
            //加载完成后的事件
            layer.Initialized += new EventHandler<EventArgs>(layer_Initialized);

            MapControl.Layers.Insert(0, layer);
            MapControl.MouseMove += new MouseEventHandler(MapControl_MouseMove);

        }

        void layer_Initialized(object sender, EventArgs e)
        {
            //一定要先移动一下 不然会有错位发生
            MapControl.ZoomTo(new ESRI.ArcGIS.Client.Geometry.Envelope(
               new MapPoint(121.2890625, 31.353636941500987).GeographicToWebMercator()
               ,
               new MapPoint(121.640625, 31.052933985705138).GeographicToWebMercator()
               ));


            PointGraphic1.Geometry = new ESRI.ArcGIS.Client.Geometry.MapPoint(121.4432, 31.1414).GeographicToWebMercator();
            PointGraphic1.Symbol = StationDownSite;
            gLayer.Graphics.Add(PointGraphic1);

        }

        private void MapControl_MouseMove(object sender, MouseEventArgs e)
        {






        }
        /// <summary>
        /// Mouse 單擊事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MapControl_MouseClick(object sender, Map.MouseEventArgs e)
        {
            var x = 0;
            var y = 0;
            var z = 0;


            var PxX = 0;
            var PxY = 0;
            var PxZ = 0;

            ///鼠標當前的坐標
            Point MousePoint = e.ScreenPoint;

            ESRI.ArcGIS.Client.Geometry.MapPoint CurrentPoint = MapControl.ScreenToMap(MousePoint).WebMercatorToGeographic();


            TileSystem.LatLongToPixelXY(CurrentPoint.Y, CurrentPoint.X, 16, out PxX, out PxY);

            TileSystem.PixelXYToTileXY(PxX, PxY, out x, out y);

            string imgName = TileSystem.TileXYToQuadKey(x, y, 16);


            if (pics.Children.Count > 10)
            {
                //移除最上一個圖片
                pics.Children.RemoveAt(10);

            }



            Image img = new Image() { Tag = imgName };
            img.MouseMove += Image_MouseMove;
            /// <summary>
            /// 用于下载的客户端
            /// </summary>
            WebClient wc = new WebClient();
            wc.OpenReadCompleted += (s, ev) =>
            {
                if (ev.Error == null)
                {
                    //实例化流资源信息，准备获取其中的图片数据
                    System.Windows.Resources.StreamResourceInfo sri = new System.Windows.Resources.StreamResourceInfo(ev.Result as System.IO.Stream, null);
                    //从流资源中获取指定的URL图片流信息
                    //StreamResourceInfo imageStream = Application.GetResourceStream(sri, new Uri(sURI));
                    System.Windows.Media.Imaging.BitmapImage imgsrc = new System.Windows.Media.Imaging.BitmapImage();
                    try
                    {
                        //绑定该URL图片信息并进行显示
                        imgsrc.SetSource(sri.Stream);
                    }
                    catch { }
                        img.Source = imgsrc;
                        pics.Children.Insert(0, img);
                    
                }
            };
            wc.OpenReadAsync(new Uri("http://localhost/tiles/a" + imgName + ".png?g=49", UriKind.Absolute));


        }


        private void ArcGISTiledMapServiceLayer_Initialized(object sender, EventArgs e)
        {

        }

        private void ArcGISTiledMapServiceLayer_InitializationFailed(object sender, EventArgs e)
        {
            MessageBox.Show("");
        }

        //先畫一個點
        Graphic PointGraphic1 = new Graphic();

        /// <summary>
        /// 畫點的圖層
        /// </summary>
        private GraphicsLayer gLayer
        {
            get { return MapControl.Layers["gLayer"] as GraphicsLayer; }
        }
        #region 定义样式 Symbols

        #region XAML原素说明 用于邦定到界面标识里的原素
        //<esriSymbols:PictureMarkerSymbol   x:Key="StationUpSite"        Source="{Binding ElementName=StationUpSiteStyle,Path=Source}"/>
        //<esriSymbols:PictureMarkerSymbol   x:Key="StationDownSite"      Source="{Binding ElementName=StationDownSiteStyle,Path=Source}"/>
        //<esriSymbols:PictureMarkerSymbol   x:Key="RouteBusCommon"       Source="{Binding ElementName=RouteBusCommonStyle,Path=Source}"/>
        //<esriSymbols:PictureMarkerSymbol   x:Key="RouteBusOffLine"      Source="{Binding ElementName=RouteBusOffLineStyle,Path=Source}"/>
        //<esriSymbols:PictureMarkerSymbol   x:Key="RouteBusError"        Source="{Binding ElementName=RouteBusErrorStyle,Path=Source}"/>
        //<esriSymbols:PictureMarkerSymbol   x:Key="DriverRequest"        Source="{Binding ElementName=DriverRequestStyle,Path=Source}"/>
        //<esriSymbols:SimpleLineSymbol      x:Key="RouteLineSymbol"        Color="{Binding ElementName=RouteLineSymbolStyle,Path=Stroke}" Width="4" Style="Solid" />
        #endregion

        /// <summary>
        /// 线路Symbol 线路颜色
        /// </summary>
        LineSymbol routeLineSymbol = null;

        /// <summary>
        /// 线路Symbol 线路颜色
        /// </summary>
        protected ESRI.ArcGIS.Client.Symbols.LineSymbol RouteLineSymbol
        {
            get
            {
                if (routeLineSymbol == null)
                {
                    routeLineSymbol = new LineSymbol();

                    //邦定  属性 
                    routeLineSymbol.SetValue(LineSymbol.ColorProperty, RouteLineSymbolStyle.Stroke);
                    routeLineSymbol.SetValue(LineSymbol.WidthProperty, RouteLineSymbolStyle.Height);
                }
                return routeLineSymbol;
            }
        }
        /// <summary>
        /// 下行站点图标 PictureMarkerSymbol
        /// </summary>
        PictureMarkerSymbol stationDownSite = null;
        /// <summary>
        /// 下行站点图标 PictureMarkerSymbol
        /// </summary>
        public PictureMarkerSymbol StationDownSite
        {
            get
            {

                if (stationDownSite == null)
                {
                    stationDownSite = new PictureMarkerSymbol();

                    //邦定  属性 
                    stationDownSite.SetValue(PictureMarkerSymbol.WidthProperty, StationDownSiteStyle.Width);
                    stationDownSite.SetValue(PictureMarkerSymbol.HeightProperty, StationDownSiteStyle.Height);
                    stationDownSite.SetValue(PictureMarkerSymbol.SourceProperty, StationDownSiteStyle.Source);

                }
                return stationDownSite;
            }
        }



        /// <summary>
        /// 上行站点图标 PictureMarkerSymbol
        /// </summary>
        PictureMarkerSymbol stationUpSite = null;

        /// <summary>
        /// 上行站点图标 PictureMarkerSymbol
        /// </summary>
        public PictureMarkerSymbol StationUpSite
        {
            get
            {
                if (stationUpSite == null)
                {
                    stationUpSite = new PictureMarkerSymbol();

                    //邦定  属性 
                    stationUpSite.SetValue(PictureMarkerSymbol.WidthProperty, StationUpSiteStyle.Width);
                    stationUpSite.SetValue(PictureMarkerSymbol.HeightProperty, StationUpSiteStyle.Height);
                    stationUpSite.SetValue(PictureMarkerSymbol.SourceProperty, StationUpSiteStyle.Source);

                }
                return stationUpSite;
            }
        }

        /// <summary>
        /// 离线车辆图标 PictureMarkerSymbol
        /// </summary>
        PictureMarkerSymbol routeBusOffLine = null;

        /// <summary>
        /// 离线车辆图标 PictureMarkerSymbol
        /// </summary>
        public PictureMarkerSymbol RouteBusOffLine
        {
            get
            {
                if (routeBusOffLine == null)
                {
                    routeBusOffLine = new PictureMarkerSymbol();

                    //邦定属性 
                    routeBusOffLine.SetValue(PictureMarkerSymbol.WidthProperty, RouteBusOffLineStyle.Width);
                    routeBusOffLine.SetValue(PictureMarkerSymbol.HeightProperty, RouteBusOffLineStyle.Height);
                    routeBusOffLine.SetValue(PictureMarkerSymbol.SourceProperty, RouteBusOffLineStyle.Source);

                }
                return routeBusOffLine;
            }
        }



        /// <summary>
        /// 一般车辆图标 PictureMarkerSymbol
        /// </summary>
        PictureMarkerSymbol routeBusCommon = null;

        /// <summary>
        /// 一般车辆图标 PictureMarkerSymbol
        /// </summary>
        public PictureMarkerSymbol RouteBusCommon
        {
            get
            {
                if (routeBusCommon == null)
                {
                    routeBusCommon = new PictureMarkerSymbol();

                    //邦定属性 
                    routeBusCommon.SetValue(PictureMarkerSymbol.WidthProperty, RouteBusCommonStyle.Width);
                    routeBusCommon.SetValue(PictureMarkerSymbol.HeightProperty, RouteBusCommonStyle.Height);
                    routeBusCommon.SetValue(PictureMarkerSymbol.SourceProperty, RouteBusCommonStyle.Source);

                }
                return routeBusCommon;
            }
        }

        /// <summary>
        /// 异常车辆图标 PictureMarkerSymbol
        /// </summary>
        PictureMarkerSymbol routeBusError = null;

        /// <summary>
        /// 异常车辆图标 PictureMarkerSymbol
        /// </summary>
        public PictureMarkerSymbol RouteBusError
        {
            get
            {
                if (routeBusError == null)
                {
                    routeBusError = new PictureMarkerSymbol();

                    //邦定属性 
                    routeBusError.SetValue(PictureMarkerSymbol.WidthProperty, RouteBusErrorStyle.Width);
                    routeBusError.SetValue(PictureMarkerSymbol.HeightProperty, RouteBusErrorStyle.Height);
                    routeBusError.SetValue(PictureMarkerSymbol.SourceProperty, RouteBusErrorStyle.Source);

                }
                return routeBusError;
            }
        }

        /// <summary>
        /// 驾驭员请求图标 PictureMarkerSymbol
        /// </summary>
        PictureMarkerSymbol driverRequest = null;

        /// <summary>
        /// 驾驭员请求图标 PictureMarkerSymbol
        /// </summary>
        public PictureMarkerSymbol DriverRequest
        {
            get
            {

                if (driverRequest == null)
                {
                    driverRequest = new PictureMarkerSymbol();

                    //邦定属性 
                    driverRequest.SetValue(PictureMarkerSymbol.WidthProperty, DriverRequestStyle.Width);
                    driverRequest.SetValue(PictureMarkerSymbol.HeightProperty, DriverRequestStyle.Height);
                    driverRequest.SetValue(PictureMarkerSymbol.SourceProperty, DriverRequestStyle.Source);

                }

                return driverRequest;
            }
        }



        #endregion

        private void Image_MouseMove(object sender, MouseEventArgs e)
        {
            #region 自己加的測試用的代碼 目前主要用來分析如何從圖片轉換出經維度

            #region 計算圖片左右兩個頂點的坐標位置
            ///圖片的高寬
            int PicWidthHeight = 256;

            Point 左上頂點 = new Point();
            Point 右下角點 = new Point();


            #region 計算當前Mouse移動在地圖中所在的px
            Point 左上頂點px = new Point();
            Point 右下頂點px = new Point();
            #endregion

            var x = 0;
            var y = 0;
            var z = 0;
            TileSystem.QuadKeyToTileXY(((FrameworkElement)sender).Tag.ToString(), out x, out y, out z);

            string Quadkey = TileSystem.TileXYToQuadKey(x, y, z);


            var PxX = 0;
            var PxY = 0;
            var PxZ = 0;
            TileSystem.TileXYToPixelXY(x, y, out PxX, out PxY);
            //得到 左上頂點px    
            左上頂點px = new Point(PxX, PxY);

            var GpsX = 0.0;
            var GpsY = 0.0;
            var GpsZ = 0.0;
            TileSystem.PixelXYToLatLong(PxX, PxY, z, out GpsX, out GpsY);

            左上頂點 = new Point() { X = GpsX, Y = GpsY };


            #region 開始計算右下角點
            TileSystem.PixelXYToLatLong(PxX + PicWidthHeight, PxY + PicWidthHeight, z, out GpsX, out GpsY);

            右下角點 = new Point() { X = GpsX, Y = GpsY };



            #endregion

            #endregion



            #endregion
            ///鼠標當前的坐標
            Point MousePoint = e.GetPosition(((UIElement)sender));
            Point PxPoint = new Point(左上頂點px.X + MousePoint.X, 左上頂點px.Y + MousePoint.Y);
            TileSystem.PixelXYToLatLong(int.Parse(PxPoint.X.ToString("f0")), int.Parse(PxPoint.Y.ToString("f0")), z, out GpsX, out GpsY);
            Point GpsPoint = new Point() { X = GpsX, Y = GpsY };

            tt.Text = "MS像素:" + PxPoint.ToString() + "\r\nMS地圖:" + GpsPoint.ToString() + "".ToString()
                + "\r\n地球:" + new MapPoint(GpsPoint.Y, GpsPoint.X).ChinaCoordTranformToWGS84()
                 + "\r\n火星:" + new MapPoint(GpsPoint.Y, GpsPoint.X).WGS84CoordTranformChina()
                ;


            #region 在地圖上標記出當前點
            ESRI.ArcGIS.Client.Geometry.MapPoint GeometryPoint = new ESRI.ArcGIS.Client.Geometry.MapPoint(GpsY, GpsX).GeographicToWebMercator();
            PointGraphic1.Geometry = GeometryPoint;
            TileSystem.LatLongToPixelXY(31.2418465244565, 121.491495538292, 16, out PxX, out PxY);
            TileSystem.PixelXYToTileXY(PxX, PxY, out x, out y);
            TileSystem.TileXYToQuadKey(x, y, 16);

            //看看当前的点在地图的范围里
            if (GeometryPoint.X <= MapControl.Extent.XMax && GeometryPoint.Y <= MapControl.Extent.YMax && GeometryPoint.X >= MapControl.Extent.XMin && GeometryPoint.Y >= MapControl.Extent.YMin)
            {

            }
            else
            {
                //如果不在范围内
                MapControl.PanTo(GeometryPoint);
                MapControl.ZoomTo(GeometryPoint);
            }

            #endregion
        }

    }


}